package com.zhang.exception;

import com.zhang.common.web.respWrapper.Res;
import com.zhang.exception.exception.NormalException;
import com.zhang.exception.exception.ParamLackException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class WebExceptionHandler{


    /**
     * 鉴权错误
     */
    @ExceptionHandler(AuthenticationException.class)
    public Res handleAuthorizationException(AuthenticationException e){
        log.debug(e.getMessage(),e);
        return Res.fail(e.getMessage());
    }

    /**
     * API错误
     */
    @ExceptionHandler(ApiException.class)
    public Res handleApiException(ApiException e){
        log.debug(e.getMessage(),e);
        return Res.fail(e.getMessage());
    }

    /**
     * 参数缺失错误
     */
    @ExceptionHandler(ParamLackException.class)
    public Res handleParamLackException(ParamLackException e){
        log.debug(e.getMessage(),e);
        return Res.fail(e.getMessage());
    }

    /**
     * 常规错误
     */
    @ExceptionHandler(NormalException.class)
    public Res handleNormalException(NormalException e){
        log.debug(e.getMessage(),e);
        return Res.fail(e.getMessage());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Res handleDataIntegrityViolationException(DataIntegrityViolationException e){
        log.debug(e.getMessage(),e);

        System.out.println("看一看报错数据是什么"+e.getMessage());
        return Res.fail("新增/更新数据错误");
    }


    /**
     * {@link javax.validation.Valid} 校验注解抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Res handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.debug(e.getMessage(),e);
        if (e.getBindingResult().getErrorCount() > 0){
            return Res.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
            return Res.fail("未知参数校验错误");
    }


    @ExceptionHandler(Exception.class)
    public Res handleException(Exception e){
        log.error(e.getMessage(),e);
        return Res.fail("未知错误，请联系开发");
    }
}
